package com.go8.mall;

import com.go8.common.util.JsonUtils;
import com.go8.mall.pojo.Cart;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.List;

@Component
public class RedisCartCache implements CartCache {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String CART_HASH_KEY = "user_carts";

    @Override
    public List<Cart> getByUserId(long userId) {
        Object json = stringRedisTemplate.opsForHash().get(CART_HASH_KEY, new Long(userId).toString());
        return JsonUtils.jsonToList((String) json, new TypeReference<List<Cart>>(){});
    }

    @Override
    public void setByUserId(long userId, List<Cart> carts) {
        if(carts.size()>0){
            stringRedisTemplate.opsForHash().put(CART_HASH_KEY,new Long(userId).toString(),
                    JsonUtils.objectToJson(carts ) );
        }else{
            stringRedisTemplate.opsForHash().delete(CART_HASH_KEY, new Long(userId).toString());
        }
    }

    @Override
    public void delByUserId(long userId) {
        stringRedisTemplate.opsForHash().delete(CART_HASH_KEY, new Long(userId).toString());
    }
}
